<script setup>
import { ref, onMounted } from 'vue'
import { getHealthListApi, getHealthByIdApi, addHealthApi, updateHealthByIdApi, delHealthByIdsApi } from '/src/api/health.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, VideoPlay, Edit, Delete } from '@element-plus/icons-vue'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
onMounted(() => {
  getList()
})

// const tableData = ref([]);
const tableData = ref([
  {
    id: 1,
    categoryId: 1,
    title: "当归生姜羊肉汤",
    imageUrl: "https://tse3-mm.cn.bing.net/th/id/OIP-C.v7tmYWYYkzinN89v_53nqgHaEL?w=284&h=180&c=7&r=0&o=7&cb=thfc1&pid=1.7&rm=3",
    description: '定位：小腿外侧，犊鼻下3寸。功效：健脾和胃，扶正培元。按摩方法：每日按压5-10分钟。',
    source: "《金匮要略》",
    videoUrl: "/src/assets/haha.mp4",
    viewCount: 66,
    praiseCount: 342,
    collectCount: 88,
    status: 1,
    createTime: "2024-01-15 08:30:45",
    updateTime: "2024-03-20 14:25:18"
  }
]);
// 控制对话框显示/隐藏
// const dialogVisible = ref(false);
//控制预览视频弹框
const videoDialogVisible = ref(false)
//控制预览照片弹框
const imageDialogVisible = ref(false)
// 存储当前要播放的视频地址
const currentVideoUrl = ref('');
// 点击封面时触发的方法
const handleVideoPlay = (videoUrl) => {
  currentVideoUrl.value = videoUrl; // 设置当前视频链接
  videoDialogVisible.value = true;       // 打开对话框
};

// 关闭对话框时暂停视频
const handleClose = () => {
  videoDialogVisible.value = false;
  currentVideoUrl.value = ''; // 清空视频链接，下次打开会重新加载
};
const searchDishInfo = ref({
  title: '',
  categoryId: '',
  status: '',
  page: 1,
  pageSize: 5
})
//加载页面
const loading = ref(false)
//一共多少数据
const total = ref(0)
//分页条背景色
const background = ref(true)
//当前页码以及当前页的total
const currentPage = ref(1)
const pageSize = ref(5)
const getList = async () => {
  const result = await getHealthListApi(searchDishInfo.value.title, searchDishInfo.value.categoryId, searchDishInfo.value.status, currentPage.value, pageSize.value)
  if (result.code) {
    tableData.value = result.data.rows
    total.value = result.data.total
    loading.value = false
  }
  else {
    tableData.value = []
  }
}
const search = () => {
  if (searchDishInfo.value.title === '' && searchDishInfo.value.categoryId === '' && searchDishInfo.value.status === '') {
    ElMessage.warning('请选择查询条件')
  }
  loading.value = true
  getList()
}
const clear = () => {
  searchDishInfo.value = {
    title: '',
    categoryId: '',
    status: '',
    page: 1,
    pageSize: 5
  }
  ElMessage.success('清空成功')
  loading.value = true
  getList()
}
//操作表格

const handleCurrentChange = () => {
  // 处理当前页变化的逻辑
  getList()
}
const handleSizeChange = () => {
  // 处理分页的总数变化的逻辑
  getList()
}
//编辑弹框显示
const dialogFormVisible = ref(false)
//新增或编辑标题
const title = ref('')
//文章分类显示下拉框显示
const categoryList = ref([{ title: '饮食', value: 1 }, { title: '作息', value: 2 }, { title: '运动', value: 3 }, { title: '防病', value: 4 }])
//文章状态显示下拉框显示
const statusList = ref([{ title: '草稿', value: 0 }, { title: '发布', value: 1 }, { title: '下架', value: 2 }])

//编辑数据回显
const dishData = ref({
  id: '',
  // id不要忘记回过来，修改的时候要用
  title: '',
  categoryId: '',
  status: '',
  imageUrl: '',
  suggest: '',
  step: ''
})
const dishFormRef = ref()
//新增文章
const addDish = () => {
  title.value = '新增文章'
  dishData.value = {
    id: '',
    title: '',
    categoryId: '',
    status: '',
    imageUrl: '',
    suggest: '',
    step: ''
  }
  // 表单校验重置
  if (dishFormRef.value) {
    dishFormRef.value.resetFields()
  }

  dialogFormVisible.value = true
}
const handleEdit = async (id) => {
  title.value = '编辑文章'
  // 表单校验重置
  if (dishFormRef.value) {
    dishFormRef.value.resetFields()
  }
  dialogFormVisible.value = true
  const result = await getHealthByIdApi(id)
  dishData.value = result.data
}

//提交数据
const submit = () => {
  //表单校验
  if (!dishFormRef.value) return
  dishFormRef.value.validate(async (valid) => {
    if (valid) {
      console.log(dishData.value);

      let result;
      //表单校验通过
      if (dishData.value.id) {
        //修改员工信息
        result = await updateHealthByIdApi(dishData.value)
        if (result.code) {
          ElMessage.success('修改成功')
          dialogFormVisible.value = false
          getList()
        } else {
          ElMessage.error(result.msg)
        }
      }
      else {
        //添加操作
        result = await addHealthApi(dishData.value)
        if (result.code) {
          ElMessage.success('添加成功')
          dialogFormVisible.value = false
          getList()
        } else {
          ElMessage.error(result.msg)
        }
      }
    } else {
      ElMessage.error('表单校验不通过！')
    }
  })
}
//获取选择的id数组
const selectIds = ref([])
//1，批量选择操作
const handleSelectionChange = (val) => {
  // console.log(val);
  //获取的是一个代理对象数组，里面有每个对象的id
  selectIds.value = val.map(item => {
    return item.id
  })
  console.log(selectIds.value);
}
//批量删除文章数据
const delDishes = () => {
  ElMessageBox.confirm(
    '你确定要删除这些吗',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      if (selectIds.value && selectIds.value.length > 0) {
        const result = await delHealthByIdsApi(selectIds.value)
        if (result.code) {
          getList()
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
        } else {
          ElMessage.error(result.msg)
        }
      } else {
        ElMessage({
          type: 'error',
          message: '请勾选数据',
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//删除文章数据
const handleDelete = (id) => {
  ElMessageBox.confirm(
    '你确定要删除吗',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const result = await delHealthByIdsApi(id)
      if (result.code) {
        getList()
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      } else {
        ElMessage.error(result.msg)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//新增表单校验
const rules = ref({
  title: [
    { required: true, message: '文章名称不能为空', trigger: 'blur' },
    { min: 2, message: '长度要大于1位', trigger: 'blur' },
  ],
  description: [
    { required: true, message: '文章内容不能为空', trigger: 'blur' },
    { min: 4, message: '长度要大于4位', trigger: 'blur' }
  ]
})
//上传照片
const uploadImageSuccess = (response) => {
  dishData.value.imageUrl = response.data
}

const beforeImageUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只支持上传图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('只能上传10M以内图片')
    return false
  }
  return true
}
//照片弹框

// const dialogVisible = ref(false)
const previewImage = ref('')

const handlePreview = (imageUrl) => {
  previewImage.value = imageUrl
  imageDialogVisible.value = true
}
//上传视频
const videoForm = ref({
  videoId: '',
  videoUrl: ''
});
const videoFlag = ref(false);
const Path = ref({
  url: 'D:\\MyProject\\Pioneer\\Intelligent-Pension-Management\\pension-back-end\\video'
});
const videoUploadPercent = ref(0);
const uploadUrl = ref('http://localhost:8080' + '/diets/videoUpload');
const beforeUploadVideo = (file) => {
  const isLt5000M = file.size / 1024 / 1024 < 5000;
  const allowedTypes = [
    'video/mp4',
    'video/ogg',
    'video/flv',
    'video/avi',
    'video/wmv',
    'video/rmvb'
  ];

  if (!allowedTypes.includes(file.type)) {
    ElMessage.error('请上传正确的视频格式');
    return false;
  }

  if (!isLt5000M) {
    ElMessage.error('上传视频大小不能超过5000MB哦!');
    return false;
  }

  return true;
};

const uploadVideoProcess = (file) => {
  Plus.value = false;
  videoFlag.value = true;
  videoUploadPercent.value = Math.round(file.percentage);
};

const handleVideoSuccess = (res) => {
  Plus.value = false;
  videoUploadPercent.value = 100;
  console.log(res);

  if (res.resCode === '200') {
    videoForm.value.videoId = res.newVidoeName;
    videoForm.value.videoUrl = res.VideoUrl;
    ElMessage.success('视频上传成功！');
  } else {
    ElMessage.error('视频上传失败，请重新上传！');
  }

  setTimeout(() => {
    resetUploadStatus();
  }, 3000);
};

const resetUploadStatus = () => {
  videoFlag.value = false;
  Plus.value = true;
  videoUploadPercent.value = 0;
};

</script>
<template>
  <PageContainer title="中医养生">
    <!-- 头部--表单 -->
    <div class="container">

      <el-form :inline="true" :model="searchDishInfo" class="demo-form-inline">
        <el-form-item label="文章标题">
          <el-input v-model="searchDishInfo.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="文章分类">
          <el-select v-model="searchDishInfo.categoryId" placeholder="请选择文章分类">
            <el-option label="饮食" value="1" />
            <el-option label="作息" value="2" />
            <el-option label="运动" value="3" />
            <el-option label="防病" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="文章状态">
          <el-select v-model="searchDishInfo.status" placeholder="请选择文章状态">
            <el-option label="草稿" value="0" />
            <el-option label="发布" value="1" />
            <el-option label="下架" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info" @click="clear">清空</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 新增、批量删除按钮-->
    <div class="container">
      <el-button type="primary" @click="addDish">+ 新增文章</el-button>
      <el-button type="info" @click="delDishes">- 批量删除</el-button>
    </div>
    <!-- 表格 -->
    <div class="container">
      <el-table :data="tableData" style="width: 100%" border v-loading="loading" element-loading-text="加载中..."
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column label="id" width="50" type="index" align="center">
        </el-table-column>
        <el-table-column label="文章标题" width="90" prop="title" align="center">
        </el-table-column>
        <el-table-column label="文章封面" width="130" prop="imageUrl" align="center">
          <template #default="scope">
            <img :src="scope.row.imageUrl" width="66px" style="cursor: pointer; object-fit: cover; border-radius: 4px;"
              @click="handlePreview(scope.row.imageUrl)">
          </template>
          <!--style="cursor: pointer; 当鼠标悬停在这张图片上时，光标会变成手型指针（👆） 
          object-fit: cover:作用控制图片在容器中的显示方式图片会按比例缩放，完全覆盖整个容器（66px × 66px）保持图片原始比例，不会变形-->
        </el-table-column>
        <el-table-column label="文章内容" width="180" prop="description" align="center">
        </el-table-column>
        <el-table-column label="文章来源" width="110" prop="source" align="center">
        </el-table-column>
        <el-table-column label="教学视频" width="130" prop="videoUrl" align="center">
          <template #default="scope">
            <!-- 使用视频元素本身作为封面 -->
            <div style="display: flex;justify-content: center;">
              <div class="video-poster" @click="handleVideoPlay(scope.row.videoUrl)">
                <video :src="scope.row.videoUrl" width="110" height="70"
                  style="border-radius: 4px; object-fit: cover; cursor: pointer;" preload="metadata"
                  ref="videoRef"></video>
                <!-- 播放图标叠加在封面上 -->
                <div class="play-icon">
                  <el-icon>
                    <VideoPlay />
                  </el-icon>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="分类" width="68" prop="categoryId" align="center">
          <template #default="scope">
            <span v-if="scope.row.categoryId === 1">饮食</span>
            <span v-else-if="scope.row.categoryId === 2">作息</span>
            <span v-else-if="scope.row.categoryId === 3">运动</span>
            <span v-else>防病</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="68" prop="status" align="center">
          <template #default="scope">
            <span v-if="scope.row.status === 0">草稿</span>
            <span v-else-if="scope.row.status === 1">发布</span>
            <span v-else>下架</span>
          </template>
        </el-table-column>
        <el-table-column label="浏览次数" width="81" prop="viewCount" align="center">
        </el-table-column>
        <el-table-column label="点赞次数" width="81" prop="praiseCount" align="center">
        </el-table-column>
        <el-table-column label="收藏次数" width="81" prop="collectCount" align="center">
        </el-table-column>
        <el-table-column label="创建时间" width="97" prop="createTime" align="center">
        </el-table-column>
        <el-table-column label="更新时间" width="97" prop="updateTime" align="center">
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template #default="scope">
            <el-button type="primary" :icon="Edit" size="small" circle plain @click="handleEdit(scope.row.id)">
            </el-button>
            <el-button type="danger" :icon="Delete" size="small" circle plain @click="handleDelete(scope.row.id)">
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页条 -->
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30]"
        :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        style="margin-top: 20px;justify-content: start;" />
    </div>

    <!-- 视频播放对话框 -->
    <el-dialog v-model="videoDialogVisible" title="视频播放" width="50%" :before-close="handleClose">
      <video :src="currentVideoUrl" controls autoplay style="width: 100%;"></video>
    </el-dialog>
    <!-- 照片预览对话框 -->
    <el-dialog v-model="imageDialogVisible" title="图片预览" width="45%" :show-close="true" top="5vh">
      <img :src="previewImage" class="preview-img" style="width: 100%;">
    </el-dialog>

    <!-- 编辑/新增文章弹框 -->
    <div class="container">
      <el-dialog v-model="dialogFormVisible" :title="title" width="700" top="4vh">
        <el-form :model="dishData" :rules="rules" ref="dishFormRef" inline="true">
          <el-form-item label="文章标题" :label-width="100" prop="title">
            <el-input v-model="dishData.title" autocomplete="off" placeholder="请输入文章名称" />
          </el-form-item>
          <el-form-item label="文章来源" :label-width="100" prop="source">
            <el-input v-model="dishData.source" autocomplete="off" placeholder="请输入文章名称" />
          </el-form-item>
          <el-form-item label="文章分类" :label-width="100">
            <el-select v-model="dishData.categoryId" placeholder="请选择" style="width: 200px;">
              <el-option v-for="category in categoryList" :label="category.title" :value="category.value"
                :key="category.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="文章状态" :label-width="100">
            <el-select v-model="dishData.status" placeholder="请选择" style="width: 200px;">
              <el-option v-for="status in statusList" :label="status.title" :value="status.value" :key="status.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="文章封面" :label-width="100">
            <el-upload class="avatar-uploader" title="file" :show-file-list="false" :auto-upload="true"
              :headers="{ 'token': token }" :on-success="uploadImageSuccess" action="/api/diets/upload"
              :before-upload="beforeImageUpload">
              <img v-if="dishData.imageUrl" :src="dishData.imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="文章视频" style="margin-top: 20px;">
            <el-upload class="video-uploader el-upload--text" :drag="Plus" :action="uploadUrl" multiple title="video"
              :show-file-list="false" :data="{ SavePath: Path.url }" @success="handleVideoSuccess"
              @before-upload="beforeUploadVideo" @progress="uploadVideoProcess">
              <i v-if="Plus" class="el-icon-upload"></i>
              <div v-if="Plus" class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <el-progress v-if="videoFlag" type="circle" :percentage="videoUploadPercent" width="80"
                style=" height:50px">
              </el-progress>
              <template #tip>
                <div class="el-upload__tip">
                  只能上传mp4/flv/avi文件,且不超过5000M
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <!--   :headers="{ 'token': token }"  -->
          <el-form-item label="文章内容" :label-width="100" style="margin-top: 40px;" prop="description">
            <el-input type="textarea" v-model="dishData.description" placeholder="请输入文章的内容"
              style="width: 400px;"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submit">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </PageContainer>
</template>

<style lang="scss" scoped>
.container {
  margin: 10px 0;

  .avatar-uploader {
    :deep() {
      .avatar {
        width: 165px;
        height: 165px;
        display: block;
      }

      .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
      }

      .el-upload:hover {
        border-color: var(--el-color-primary);
      }

      .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 165px;
        height: 165px;
        text-align: center;
      }
    }
  }

  .video-poster {
    position: relative;
    /* 为播放图标定位提供参考 */
    display: inline-block;
    cursor: pointer;
  }

  .play-icon {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    /* 居中 */
    color: #fff;
    font-size: 30px;
    text-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
    opacity: 0.8;
    transition: opacity 0.3s;
  }

  .video-poster:hover .play-icon {
    opacity: 1;
    /* 鼠标悬停时图标更清晰 */
  }

  //上传视频
  .video-uploader {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 200px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .video-uploader:hover {
    border-color: #409EFF;
  }

  .el-upload__text {
    font-size: 14px;
    color: #606266;
    margin-top: 10px;
  }

  .el-upload__tip {
    font-size: 12px;
    color: #606266;
    margin-top: 10px;
  }

  // .el-form-item {
  //   margin-bottom: 30px;
  // }
}


.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
